#!/usr/bin/env python
from sinastorage.bucket import SCSBucket
import sinastorage
import requests

class IPAddr:
    def __init__(self):
        self.req_url="http://moqiancong.applinzi.com/ipaddr"
    def read(self):
        ipaddr=requests.get(self.req_url)
        return ipaddr.text

class SaeBucket:
    def __init__(self):
        #setting access_key,secret_key
        ac_key="jt25j9XlYSMCuqWaJMz1"
        sec_key="8cbb96e745caae84d2622ce6f88727c925a93cf4"
        usr_id="SINA0000000000JT25J9"
        bucket_name="moqiancong"
        sinastorage.setDefaultAppInfo(ac_key,sec_key)
        self.s = SCSBucket(bucket_name,secure=True) # secure=True for https access

    def write(self,prefix, content):
        return self.s.put(prefix, content)

    def read(self, prefix, CHUNK_LEN=512):
        import StringIO
        out_buf=StringIO.StringIO()
        response = self.s[prefix]
        while True:
            chunk = response.read(CHUNK_LEN)
            if not chunk: break
            out_buf.write(chunk)
        return out_buf.getvalue()

def SaveAddr(store_name, others):
    import datetime
    bucket = SaeBucket()
    ipaddr = IPAddr().read()
    time=str(datetime.datetime.now())
    prefix='/ipaddr/%s'%store_name
    if len(others)==0:
        content = '{"addr":"%s", "time":"%s"}'%(ipaddr,time)
    else:
        content = '{"addr":"%s","time":"%s", "others":%s}'%(ipaddr, time, others)
    content = content.replace("'", "\"")
    bucket.write(prefix, content)

def LoadAddr(store_name):
    bucket = SaeBucket()
    prefix='/ipaddr/%s'%store_name
    return bucket.read(prefix)

if __name__ == "__main__":
    import sys
    action=sys.argv[1]
    store_name=sys.argv[2]
    others = sys.argv[3:]
    if action=="save":
        SaveAddr(store_name, others)
    elif action=="load":
        print(LoadAddr(store_name))
    else:
        print("Action Error!")
    




